package com.haorui.lygyd.authority.service;

import com.haorui.base.system.entity.Account;
import com.haorui.base.system.service.AccountService;
import com.haorui.base.system.service.RoleAndpermissionsService;
import com.haorui.base.system.service.UserAndRoleService;
import com.haorui.lygyd.authority.dto.AuthAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2017/8/10
 * 时间: 14:17
 * 功能：请进行修改
 */
@Service("accountDetailServicec")
public class AccountDetailService implements UserDetailsService {

    @Autowired
    private AccountService accountService;
    @Autowired
    private UserAndRoleService userAndRoleService;
    @Autowired
    private RoleAndpermissionsService roleAndpermissionsService;

    @Override
    public AuthAccount loadUserByUsername(String userName) throws UsernameNotFoundException {
        Account account=accountService.findAccountByUserName(userName);
        if(account==null){
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", userName));
        }
        SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(account.getAccountType().getCode());
        Set<GrantedAuthority> set=new HashSet<GrantedAuthority>();
        set.add(simpleGrantedAuthority);
        AuthAccount authAccount= new AuthAccount(account.getId(),account.getUserName(),account.getPassword(),account.getEmail(),set,new Date());
        authAccount.setAccountType(account.getAccountType());
        authAccount.setPhoto(account.getPhoto());
        authAccount.setOrgId(account.getOrgid());
        authAccount.setOrgName(account.getOrgName());
        return authAccount;
    }
}
